from django.shortcuts import render_to_response, get_object_or_404
from django.conf import settings
from django.template import RequestContext
from django.views.generic.list_detail import object_list, object_detail
from django.views.generic.create_update import create_object
from django.db.models import F
from django.db import connection

from logdjango.models import Entry
from logdjango.forms import EntryForm, LogMessageForm

import logging

def home(request, template_name='home.html'):
    """
    Example view with some logging.
    """
    logging.info("Running home view!")
    entry_list_info = {
        'template_name': template_name,
        'template_object_name': 'entry',
        'queryset': Entry.objects.all(),
    }
    return object_list(request, **entry_list_info)

def entry_create(request, template_name='entry_create.html'):
    """
    Creation of entry view.
    """
    create_object_info = {
        'form_class': EntryForm,
        'template_name': template_name,
        'login_required': False,
    }
    return create_object(request, **create_object_info)

def entry_details(request, entry_id, template_name='entry_details.html'):
    """
    Shows details of the entry object.
    """
    logging.info("Requesting details of the entry with id=%s" % entry_id)
    entry = get_object_or_404(Entry, id=entry_id)
    entry.hit()

    data = {
        'entry': entry,
    }
    return render_to_response(template_name, data, RequestContext(request))

def show_log_file(request, template_name='log_content.html'):
    """
    Shows content of the logging file defined
    at DJALOG_FILE in settings module.
    """
    logging.info("Running show_log_file view!")
    try:
        log = open(settings.DJALOG_FILE).read()
    except IOError, err:
        logging.error("Couldn't access log file! Error: %s" % err)
    except AttributeError, err:
        logging.error("DJALOG_FILE attribute is not present at "
            "settings module. Is djalog really loaded?")
    
    data = {
        'log': log,
    }
    return render_to_response(template_name, data, RequestContext(request))

def log_message(request, template_name='log_message.html'):
    """
    Logs message on the given level.
    """
    data = {}
    form = LogMessageForm(request.POST or None)
    if request.method == 'POST' and form.is_valid():
        cleaned_data = form.cleaned_data
        log_level = cleaned_data['log_level']
        message = cleaned_data['message']
        logging.log(log_level, message)
        data['message'] = message
        data['log_level'] = log_level
        data['log_name'] = logging._levelNames[log_level]
    data['form'] = form

    return render_to_response(template_name, data, RequestContext(request))

def log_all_levels(request, template_name='log_all_levels.html'):
    """
    Logs message on every possible level.
    """
    pass

